package cn.com.joycode.nimble.web.servlet;

import cn.com.joycode.nimble.core.message.NbMsg;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author Max Woods
 * @since 1.0
 */


@Slf4j
public class ServletUtil extends cn.hutool.extra.servlet.ServletUtil {

    /**
     * 是否浏览器请求
     *
     * @param httpServletRequest
     * @return
     */
    public static boolean isBrowserRequest(HttpServletRequest httpServletRequest) {
        String userAgent = httpServletRequest.getHeader(Header.USER_AGENT.toString());
        String contentType = httpServletRequest.getHeader(Header.CONTENT_TYPE.toString());
        boolean result = StrUtil.isNotBlank(userAgent) && StrUtil.isBlank(contentType);
        return result;
    }

    /**
     * 是否RestApi请求
     *
     * @param httpServletRequest
     * @return
     */
    public static boolean isJsonRequest(HttpServletRequest httpServletRequest) {
        String contentType = httpServletRequest.getHeader(Header.CONTENT_TYPE.toString());
        return StrUtil.containsIgnoreCase(contentType, ContentType.JSON.toString());
    }

    /**
     * 是否ajax请求
     *
     * @param httpServletRequest
     * @return
     */
    public static boolean isAjaxRequest(HttpServletRequest httpServletRequest) {
        String header = httpServletRequest.getHeader("X-Requested-With");
        return StrUtil.equalsIgnoreCase(header, "XMLHttpRequest");
    }

    public static String getBearerAuthorization(HttpServletRequest httpServletRequest) {
        String authInfo = httpServletRequest.getHeader("Authorization");
        return StrUtil.removePrefix(authInfo, "Bearer ");
    }

    public static void writeResponse(HttpServletResponse httpServletResponse, NbMsg nbMsg) throws IOException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.getWriter().print(nbMsg.toString());
        httpServletResponse.getWriter().flush();
    }

    public static void writeResponse(HttpServletResponse httpServletResponse, int status, NbMsg nbMsg) throws IOException {
        httpServletResponse.setStatus(status);
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.getWriter().print(nbMsg.toString());
        httpServletResponse.getWriter().flush();
    }

    public static String getIpAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    log.error("未知主机", e);
                }
                ipAddress = inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        //"***.***.***.***".length() = 15
        if (ipAddress != null && ipAddress.length() > 15) {
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }


    public static String getLocalIp() throws UnknownHostException {
        String localIP = "";
        InetAddress addr = (InetAddress) InetAddress.getLocalHost();
        localIP = addr.getHostAddress().toString();
        return localIP;
    }
}